package com.styletransfer.mapper;

import com.styletransfer.model.Notification;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 通知数据访问接口
 */
@Mapper
public interface NotificationMapper {

    /**
     * 插入通知
     *
     * @param notification 通知对象
     * @return 影响行数
     */
    @Insert("INSERT INTO notification (user_id, from_user_id, type, content, resource_id, is_read, create_time, update_time) " +
            "VALUES (#{userId}, #{fromUserId}, #{type}, #{content}, #{resourceId}, #{isRead}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Notification notification);

    /**
     * 根据ID查询通知
     *
     * @param id 通知ID
     * @return 通知对象
     */
    @Select("SELECT * FROM notification WHERE id = #{id}")
    Notification findById(Long id);

    /**
     * 根据用户ID查询通知列表（分页）
     *
     * @param userId 用户ID
     * @param offset 偏移量
     * @param limit 限制数
     * @return 通知列表
     */
    @Select("SELECT n.*, u.username as from_user_name, u.avatar as from_user_avatar " +
            "FROM notification n " +
            "LEFT JOIN user u ON n.from_user_id = u.id " +
            "WHERE n.user_id = #{userId} " +
            "ORDER BY n.create_time DESC " +
            "LIMIT #{limit} OFFSET #{offset}")
    List<Notification> findByUserId(Long userId, int offset, int limit);

    /**
     * 根据用户ID统计通知数量
     *
     * @param userId 用户ID
     * @return 通知数量
     */
    @Select("SELECT COUNT(*) FROM notification WHERE user_id = #{userId}")
    int countByUserId(Long userId);

    /**
     * 根据用户ID统计未读通知数量
     *
     * @param userId 用户ID
     * @return 未读通知数量
     */
    @Select("SELECT COUNT(*) FROM notification WHERE user_id = #{userId} AND is_read = 0")
    int countUnreadByUserId(Long userId);

    /**
     * 标记通知为已读
     *
     * @param id 通知ID
     * @return 影响行数
     */
    @Update("UPDATE notification SET is_read = 1, update_time = NOW() WHERE id = #{id}")
    int markAsRead(Long id);

    /**
     * 标记用户所有通知为已读
     *
     * @param userId 用户ID
     * @return 影响行数
     */
    @Update("UPDATE notification SET is_read = 1, update_time = NOW() WHERE user_id = #{userId}")
    int markAllAsRead(Long userId);

    /**
     * 删除通知
     *
     * @param id 通知ID
     * @return 影响行数
     */
    @Delete("DELETE FROM notification WHERE id = #{id}")
    int delete(Long id);
}
